package com.promotores;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.json.JSONException;

import com.promotores.util.Parametros;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;


public class ActivityAsignarNuevaPromocion extends Activity implements OnClickListener {
	
	private Button btnfecini;
	private Button btnfecfin;
	private Button btnregistrar;
	private Button btncancelar;
	private int flag_btnfec;
	private int mYear1;
    private int mMonth1;
    private int mDay1;
    private int mYear2;
    private int mMonth2;
    private int mDay2;
    private int mYearAnt1;
    private int mMonthAnt1;
    private int mDayAnt1;
    private int mYearAnt2;
    private int mMonthAnt2;
    private int mDayAnt2;
    private String textFecha;
    private String textFecha2;
    static final int DATE_DIALOG_ID = 0;
	private BeanPromocion promocion;
	private String flagDescuento="";
	Date dt = new Date();
	SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
	int idTipoPromocion;
	int idEvento;
	String fechaIni;
	String fechaFin;
	String nombEvento;
	java.sql.Date fechaSQL;
	   
	/**
	 * @see android.app.Activity#onCreate(Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {		
		
		super.onCreate(savedInstanceState);
		idTipoPromocion = Integer.parseInt(getIntent().getStringExtra("idTipoPromocion"));
		idEvento = Integer.parseInt(getIntent().getStringExtra("idEvento"));
		fechaIni = getIntent().getStringExtra("fechaini");
		fechaFin = getIntent().getStringExtra("fechafin");	
		nombEvento = getIntent().getStringExtra("nombEvento");
		Log.e("tamare", idTipoPromocion + " " + idEvento);
		setContentView(R.layout.pr_asignar_promocion);
		TextView txtTitulo = new TextView(this); 
		txtTitulo = (TextView)findViewById(R.id.titNombEvento);
		txtTitulo.setText("Evento: "+nombEvento);
		btnfecini = (Button) findViewById(R.id.btnfecini);
		btnfecfin = (Button) findViewById(R.id.btnfecfin);
		btnregistrar = (Button) findViewById(R.id.btnregistrar);
		btnregistrar.setOnClickListener(this);
		
		
		btnfecini.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	flag_btnfec = 1;
                showDialog(1);
            }
        });		
		btnfecfin.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	flag_btnfec = 2;
                showDialog(2);
            }
        });		
		fechaIni = fechaIni.substring(0, 4)  + '/' + fechaIni.substring(5, 7)
				   +  '/' + fechaIni.substring(8, 10);
		fechaFin = fechaFin.substring(0, 4)  + '/' + fechaFin.substring(5, 7)
				   +  '/' + fechaFin.substring(8, 10);
		btnfecini.setText(fechaIni);
		btnfecfin.setText(fechaIni);
		
        mYear1 = Integer.parseInt(fechaIni.substring(0, 4));
        mMonth1 = Integer.parseInt(fechaIni.substring(5, 7))-1;
        mDay1 = Integer.parseInt(fechaIni.substring(8, 10));
        mYear2 = Integer.parseInt(fechaIni.substring(0, 4));
        mMonth2 = Integer.parseInt(fechaIni.substring(5, 7))-1;
        mDay2 = Integer.parseInt(fechaIni.substring(8, 10));
//        mYear2 = Integer.parseInt(fechaIni.substring(0, 4));
//        mMonth2 = Integer.parseInt(fechaIni.substring(5, 7));
//        mDay2 = Integer.parseInt(fechaIni.substring(8, 10));
		ImageButton offline = (ImageButton)findViewById(R.id.imgOfflineMode);
        offline.setOnClickListener(this);
        if (Parametros.isOffline_mode()){
        	offline.setVisibility(View.VISIBLE);
        }
	}
	  
	private void updateDisplay() throws ParseException {
		Date dateObj = null;
		Date dateObj2 = null;
		if ( flag_btnfec == 1 ){
		  
		  String auxMes = String.valueOf(mMonth1+1);
		  if (auxMes.length()==1) auxMes = "0"+auxMes;
		  String auxDia = String.valueOf(mDay1);
		  if (auxDia.length()==1) auxDia = "0"+auxDia;
		  
		  textFecha =  String.valueOf(mYear1) + '/' +  auxMes + '/' + auxDia;
		  SimpleDateFormat curFormater = new SimpleDateFormat("yyyy/MM/dd"); 
		  dateObj = curFormater.parse(textFecha); 
		  Date dateFinObj = curFormater.parse((String)btnfecfin.getText());
		  Date dateini = curFormater.parse(fechaIni);
		  Date datefin = curFormater.parse(fechaFin);
		  
		  if (dateObj.compareTo(dt) < 0){
			  Toast.makeText(this, "La fecha debe ser mayor o igual a la fecha actual", Toast.LENGTH_LONG).show();
		  } 
		  else if(dateObj.compareTo(dateini)< 0){
			  Toast.makeText(this, "La fecha debe ser mayor o igual a la fecha de inicio de la venta", Toast.LENGTH_LONG).show();  
		  } 		  
		  else if(dateObj.compareTo(datefin)>0) {
			  Toast.makeText(this, "La fecha debe ser menor o igual a la fecha de fin de la venta", Toast.LENGTH_LONG).show();
		  }
		  else if(dateObj.compareTo(dateFinObj)>0) {
			  Toast.makeText(this, "La fecha debe ser menor o igual a la fecha de fin de la promocion", Toast.LENGTH_LONG).show();
		  }
		  else {
			  btnfecini.setText(textFecha);
			  return;
		  }
		  mYear1 = mYearAnt1;
		  mMonth1 = mMonthAnt1;
		  mDay1 = mDayAnt1;
	  }	  
	  if ( flag_btnfec == 2 ){
		  
		  String auxMes = String.valueOf(mMonth2+1);
		  if (auxMes.length()==1) auxMes = "0"+auxMes;
		  String auxDia = String.valueOf(mDay2);
		  if (auxDia.length()==1) auxDia = "0"+auxDia;
		  
		  textFecha =  String.valueOf(mYear2) + '/' +  auxMes + '/' + auxDia;
		  SimpleDateFormat curFormater = new SimpleDateFormat("yyyy/MM/dd"); 
		  Date dateIniObj = curFormater.parse((String)btnfecini.getText());
		  dateObj2 = curFormater.parse(textFecha); 
		  Date datefin = curFormater.parse(fechaFin); 
		  if (dateObj2.compareTo(dt) < 0){
			  Toast.makeText(this, "La fecha debe ser mayor o igual a la fecha actual", Toast.LENGTH_LONG).show();
		  } 
		  else if(dateObj2.compareTo(dateIniObj)< 0){
			  Toast.makeText(this, "La fecha debe ser mayor o igual a la fecha de inicio de la promocion", Toast.LENGTH_LONG).show();  
		  } 
		  else if(dateObj2.compareTo(datefin)> 0){
			  Toast.makeText(this, "La fecha debe ser menor o igual a la fecha de fin de la venta", Toast.LENGTH_LONG).show();  
		  } 
		  else{
			  btnfecfin.setText(textFecha);
			  return;
		  }
		  mYear2 = mYearAnt2;
		  mMonth2 = mMonthAnt2;
		  mDay2 = mDayAnt2;
	  }	
    }		  
	  	            
    // the callback received when the user "sets" the date in the dialog
    private DatePickerDialog.OnDateSetListener mDateSetListener =
            new DatePickerDialog.OnDateSetListener() {

            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            	if ( flag_btnfec == 1 ){
//            		mYearAnt = mYear1;
//            		mMonthAnt = mMonth1;
//            		mDayAnt = mDay1;
            		mYear1 = year;
            		mMonth1 = monthOfYear;
                    mDay1 = dayOfMonth;                    
            	} else if ( flag_btnfec == 2 ){
//            		mYearAnt = mYear2;
//            		mMonthAnt = mMonth2;
//            		mDayAnt = mDay2;
            		mYear2 = year;
            		mMonth2 = monthOfYear;
                    mDay2 = dayOfMonth;                    
            	}
                try {
					updateDisplay();
					//dismiss();
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
            }
    };
       
  
    DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
	    @Override
	    public void onClick(DialogInterface dialog, int which) {
	        switch (which){
	        case DialogInterface.BUTTON_POSITIVE:
	        	//finish();
	            break;
                        	       
	        }
	    }
	};   
            
	@Override
	protected Dialog onCreateDialog(int id) {
		SimpleDateFormat curFormater = new SimpleDateFormat("yyyy/MM/dd");
		switch (id) {
		case 1:
			try {
				//Date dateIniObj = curFormater.parse((String)btnfecini.getText());
				//String dateAux = dateIniObj.toString();
//				String dateAux = (String)btnfecini.getText();
//				mYear1 = Integer.parseInt(dateAux.substring(0, 4));
//		        mMonth1 = Integer.parseInt(dateAux.substring(5, 7))-1;
//		        mDay1 = Integer.parseInt(dateAux.substring(8, 10));
				mYearAnt1 = mYear1;
        		mMonthAnt1 = mMonth1;
        		mDayAnt1 = mDay1;
		        return new DatePickerDialog(this, mDateSetListener, mYear1, mMonth1, mDay1);			
			}
			catch (Exception e){
				return null;
			}			
		case 2:
			try {
				//Date dateFinObj = curFormater.parse((String)btnfecfin.getText());
				//String dateAux = dateFinObj.toString();
//				String dateAux = (String)btnfecfin.getText();
//				mYear2 = Integer.parseInt(dateAux.substring(0, 4));
//		        mMonth2 = Integer.parseInt(dateAux.substring(5, 7))-1;
//		        mDay2 = Integer.parseInt(dateAux.substring(8, 10));
				mYearAnt2 = mYear2;
        		mMonthAnt2 = mMonth2;
        		mDayAnt2 = mDay2;
				return new DatePickerDialog(this, mDateSetListener, mYear2, mMonth2, mDay2);
			}
			catch (Exception e){
				return null;
			}
		}
		return null;
	}

	@Override
	public void onClick(View v) {
		
		if (v.getId()==R.id.btnregistrar){
			EditText etxt = (EditText)findViewById(R.id.edtpordescuento);
			if (etxt.getText().toString()==null || etxt.getText().toString().compareTo("")==0){
				Toast.makeText(this, "Ingrese un valor de descuento", Toast.LENGTH_LONG).show();
				return;
			}
			promocion = obtieneDatos();
			int registrar = 0;
			int idLocal = 0;
			GestorPromocion dbPromocion = new GestorPromocion(this);
			if (flagDescuento.compareTo("1") == 0){
				Toast.makeText(this, "El descuento debe ser mayor que 0", Toast.LENGTH_LONG).show();
				return;
			}
		    else if (flagDescuento.compareTo("2") == 0){	
			    Toast.makeText(this, "El descuento debe ser menor o igual a 100", Toast.LENGTH_LONG).show();
			    return;
		    } 
			
			registrar = dbPromocion.verificarRegistro(idEvento, idTipoPromocion, promocion.getFecIni(), promocion.getFecFin());
			if ( registrar > 0 ){
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setMessage("No se puede guardar la promocion entre el rango de fechas seleccionado").setPositiveButton("Aceptar", dialogClickListener).show();
				return;
			} 
			else
			{
				idLocal = dbPromocion.addPromocion(promocion);
				Log.e("addBDpromo","id:"+promocion.getIdLocal()+";idS:"+promocion.getId()+";desc:"+promocion.getDescuento());
				promocion.setIdLocal(idLocal);
			}
			
			JsonPromocion jPromocion = new JsonPromocion();
			try {
				BeanPromocionResponse result = jPromocion.postData(promocion);
				Parametros.setOffline_mode(true);
				if (result!=null) {
					promocion.setId(result.getId());
					promocion.setUpdated_at(result.getUpdated_at());
					promocion.setCreated_at(result.getCreated_at());
					dbPromocion.setId(promocion);
					Log.e("addIdPromo","idL:"+promocion.getIdLocal()+";idS:"+promocion.getId());
					dbPromocion.setSaved(promocion);
					dbPromocion.setFechas(promocion);
					Parametros.setOffline_mode(false);
				}
				if (result==null && !isNetworkAvailable())
					Toast.makeText(getApplicationContext(), "Modo Offline Activado\nNo hay conexión disponible", Toast.LENGTH_LONG).show();
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
//			Intent intent = new Intent();
//			   intent.putExtra("idEvento", idEvento);
//			   intent.setClass(this, ActivityListarPromociones.class);
//			   startActivity(intent);
			finish();		    		
		}
	}
	
	
	
	private BeanPromocion obtieneDatos(){
		
		GestorTipoPromocion dbTipoPromocion = new GestorTipoPromocion(this);
		BeanTipoPromocion tipoPromocion = dbTipoPromocion.getTipoPromocion(idTipoPromocion);
		
		GestorEvento dbEvento = new GestorEvento(this);
		BeanEvento evento = dbEvento.getEvento(idEvento);  
		
		EditText desc_aux =  (EditText)findViewById(R.id.edtpordescuento);
		int desc = Integer.parseInt(desc_aux.getText().toString());
	    
		if (desc < 1){
			flagDescuento = "1";
			
		}else if (desc > 100){
			flagDescuento = "2";
			
		}
		
		TextView t=new TextView(this);
	    t=(TextView)findViewById(R.id.btnfecini);
	    String fechaIni = (String)t.getText();
	    t=(TextView)findViewById(R.id.btnfecfin);
	    String fechaFin = (String)t.getText();
	    
	    String dias = "";
	    CheckBox cb = (CheckBox)findViewById(R.id.checkBox1);
	    if (cb.isChecked())
	    	dias = dias + "1";
	    else
	    	dias = dias + "0";
	    cb = (CheckBox)findViewById(R.id.checkBox2);
	    if (cb.isChecked())
	    	dias = dias + "1";
	    else
	    	dias = dias + "0";
	    cb = (CheckBox)findViewById(R.id.checkBox3);
	    if (cb.isChecked())
	    	dias = dias + "1";
	    else
	    	dias = dias + "0";
	    cb = (CheckBox)findViewById(R.id.checkBox4);
	    if (cb.isChecked())
	    	dias = dias + "1";
	    else
	    	dias = dias + "0";
	    cb = (CheckBox)findViewById(R.id.checkBox5);
	    if (cb.isChecked())
	    	dias = dias + "1";
	    else
	    	dias = dias + "0";
	    cb = (CheckBox)findViewById(R.id.checkBox6);
	    if (cb.isChecked())
	    	dias = dias + "1";
	    else
	    	dias = dias + "0";
	    cb = (CheckBox)findViewById(R.id.checkBox7);
	    if (cb.isChecked())
	    	dias = dias + "1";
	    else
	    	dias = dias + "0";
	    
	    Log.e("asignarPromo", idTipoPromocion + idEvento + fechaIni + fechaFin + String.valueOf(desc) + dias);
		GestorPromocion dbPromo = new GestorPromocion(this);
		
		//Revisar el id que se obtiene.
		
		BeanPromocion promocion = new BeanPromocion();
		//promocion.setIdLocal(idLocal);
		promocion.setTipoPromocion(tipoPromocion);
		promocion.setEvento(evento);
		promocion.setFecIni(fechaIni);
		promocion.setFecFin(fechaFin);
		promocion.setDescuento(desc);
		promocion.setDias(dias);
		promocion.setSaved("0");
		promocion.setDeleted("0");
		return promocion;
	}

			
	private boolean isNetworkAvailable() {
	    ConnectivityManager connectivityManager 
	          = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
	    return activeNetworkInfo != null;
	}
	        	            
}
